package com.zhuiyun.educations.api.video.service.impl;

import com.zhuiyun.educations.api.video.entity.FileMerge;
import com.zhuiyun.educations.api.video.mapper.VideoMapper;
import com.zhuiyun.educations.api.video.service.VideoService;
import com.zhuiyun.educations.common.errorCode.CommonException;
import com.zhuiyun.educations.common.errorCode.EmErrorCode;
import com.zhuiyun.educations.common.response.CommonResult;
import com.zhuiyun.educations.config.VariableConfig;
import com.zhuiyun.educations.util.StringUtils;
import com.zhuiyun.educations.util.pageUtil.MybatisPageHelper;
import com.zhuiyun.educations.util.pageUtil.PageRequest;
import com.zhuiyun.educations.util.pageUtil.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @ClassName VideoServiceImpl
 * @Description TODO
 * @Author 杨友朋
 * @Date 2023/7/7 9:48
 **/
@Service
public class VideoServiceImpl implements VideoService {
    @Resource
    VideoMapper videoMapper;

    @Autowired
    private VariableConfig variableConfig;

    /**
    * @Author 杨友朋
    * @Description TODO 分页全查
    * @Date 2023/7/7 15:06
    * @Return
    * @param pageRequest
    */
    @Override
    public PageResult selectVideo(PageRequest pageRequest) {
        MybatisPageHelper.startPage(pageRequest);
        List<FileMerge> fileMerges = videoMapper.selectAll();
        return MybatisPageHelper.getPageResult(fileMerges);
    }

    /**
    * @Author 杨友朋
    * @Description TODO 全查
    * @Date 2023/7/7 15:06
    * @Return
    * @param
    */
    @Override
    public List<FileMerge> selectAll() {
        return videoMapper.selectAll();
    }

    @Override
    public FileMerge selectById(Integer id) {
        if(id!=null){
            return videoMapper.selectById(id);
        }else {
            return null;
        }

    }

    @Override
    public void getVideoById(HttpServletResponse response, Integer id) throws CommonException, FileNotFoundException {
        if(StringUtils.isNotEmpty(id)){
            // 获取我呢见对象
            FileMerge fileManage = videoMapper.selectById(id);
            System.out.println("+++++++++++++"+fileManage);
            if(fileManage!=null&&variableConfig.getVideoType().contains(fileManage.getFileType())){
                // 拼接图片路径
                File file = new File(fileManage.getFilePath());
                if(file.exists()){
                    RandomAccessFile targetFile = new RandomAccessFile(file, "r");
                    OutputStream os = null;
                    try {
                        //设置响应头，把文件名字设置好
                        response.setContentType("application/octet-stream;charset=UTF-8");
                        String fileName = new String(fileManage.getFilename().getBytes(), "iso8859-1");
                        response.setHeader("Content-disposition", "inline;filename=" + fileName);
                        //设置文件长度
                        response.setHeader("Content-Length", String.valueOf(fileManage.getTotalSize()));
                        //解决编码问题

                        byte[] cache = new byte[(int) file.length()];
                        // 获取输出流
                        os = response.getOutputStream();
                        int flag;
                        while ((flag = targetFile.read(cache))!=-1){
                            os.write(cache, 0, flag);
                        }
                        os.flush();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        // 关闭流
                        closeIO(os,null);
                    }
                }else{
                    throw new CommonException(EmErrorCode.VIDEO_NOT_EXISTS);
                }
            }else{
                throw new CommonException(EmErrorCode.VIDEO_NOT_EXISTS);
            }

        }else {
            throw new CommonException(EmErrorCode.ID_NULL);
        }

    }

    /**
     * 关闭 输出输入流
     * @param os
     * @param fis
     */
    public void closeIO(OutputStream os,FileInputStream fis){
        // 关闭文件输入流
        if(fis!=null){
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        // 关闭输出流
        if(os!=null){
            try {
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
